<template>
    <div class="flow-list">
        <search-table
            :columns="columns"
            :data="flowList"
            :total="total"
            :size.sync="search.pageSize"
            :page.sync="search.pageIndex"
            @queryFun="queryflowList">
            <template slot="input-group">
                <DatePicker :editable="false" type="datetimerange" :value="dates" class="time"
                    format="yyyy-MM-dd HH:mm" placement="bottom-start" confirm ref="datePicker"
                    placeholder="选择起止时间" style="width: 250px" transfer :options="disabledOptions"
                    @on-ok="clickOkBtn" :clearable="false"
                    @on-open-change="switchOpenChange" @on-change="changeDates"></DatePicker>
            </template>
            <template slot="select-group">
                <Select filterable
                    v-model="search.dstDeviceId"
                    placeholder="请选择源"
                    filterable
                    clearable
                    @on-change="changePage(1)">
                    <Option  v-for="item in dstDevicesOption" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
                </Select>
                <Select filterable
                    v-model="search.srcDeviceId"
                    placeholder="请选择目标"
                    filterable
                    clearable
                    @on-change="changePage(1)">
                    <Option  v-for="item in srcDevicesOption" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
                </Select>
            </template>
        </search-table>
    </div>
</template>

<script>
    import SearchTable from '@/components/SearchTable/SearchTable'
    import { queryflowList, queryflowfilter } from '@/api/drill'
    import { format } from '@/libs/utils'

    export default {
        name: 'FlowList',
        components: {
            SearchTable
        },
        data() {
            return {
                dates: [],
                disabledOptions: {
                    // disabledDate(date) {
                    //     return date && date.valueOf() < Date.now() - 86400000;
                    // }
                },
                loading: false,
                columns: [
                    {
                        placement: 'top-left',
                        title: '源设备名称',
                        key: 'dstDeviceName',
                        align: 'center',
                        tooltip: true,
                        width: 180
                    },
                    {
                        placement: 'top-left',
                        title: '源设备类型',
                        key: 'dstDeviceType',
                        align: 'center',
                        tooltip: true,
                        width: 180
                    },
                    {
                        placement: 'top-left',
                        title: '目标设备名称',
                        key: 'srcDeviceName',
                        align: 'center',
                        tooltip: true,
                        width: 180
                    },
                    {
                        placement: 'top-left',
                        title: '目标设备类型',
                        key: 'srcDeviceType',
                        align: 'center',
                        tooltip: true,
                        width: 180
                    },
                    {
                        title: '源设备Mac',
                        width: 140,
                        key: 'dstMac',
                        tooltip: true
                    },
                    {
                        title: '源设备Ip',
                        width: 120,
                        key: 'dstIp',
                        tooltip: true
                    },
                    {
                        title: '源设备Port',
                        width: 80,
                        key: 'dstPort',
                        tooltip: true
                    },
                    {
                        title: '目标设备Mac',
                        width: 140,
                        key: 'srcMac',
                        tooltip: true
                    },
                    {
                        title: '目标设备Ip',
                        width: 120,
                        key: 'srcIp',
                        tooltip: true
                    },
                    {
                        title: '目标设备Port',
                        width: 80,
                        key: 'srcPort',
                        tooltip: true
                    },
                    {
                        title: '生成时间',
                        width: 140,
                        key: 'timestamp',
                        tooltip: true
                    }
                ],
                search: {
                    dstDeviceId: '',
                    srcDeviceId: '',
                    startTime: '',
                    endTime: '',
                    projectId: this.$route.query.prjid,
                    pageSize: 10,
                    pageIndex: 1
                },
                dstDevices: [],
                srcDevices: [],
                total: 0, // 总数据量
                isClickOkBtn: false,
                flowList: [] // 流量列表
            }
        },
        mounted() {
            let now = new Date()
            this.search.endTime = format(new Date(now))
            this.search.startTime = format(new Date(now - 3600000))
            this.dates = [this.search.startTime, this.search.endTime]
            this.changePage(1)
            this.queryflowfilter()
        },
        computed: {
            dstDevicesOption() {
                let ret = [], ids = []
                this.dstDevices.forEach(item => {
                    if (!ids.includes(item.id)) {
                        ret.push(item)
                        ids.push(item.id)
                    }
                })
                return ret
            },
            srcDevicesOption() {
                let ret = [], ids = []
                this.srcDevices.forEach(item => {
                    if (!ids.includes(item.id)) {
                        ret.push(item)
                        ids.push(item.id)
                    }
                })
                return ret
            }
        },
        methods: {
            // 点击确认按钮关闭DatePicker组件时，标记状态
            clickOkBtn() {
                this.isClickOkBtn = true
            },
            changeDates(timeList) {
                this.dates = timeList
            },
            // 切换DatePicker组件显示/关闭的状态
            switchOpenChange(isOpen) {
                this.$nextTick(() => {
                    if (isOpen) { // 显示组件
                        this.isClickOkBtn = false
                        this.originalTime = this.dates
                    } else { // 隐藏操作
                        if (!this.isClickOkBtn) { // 不是通过点击确认按钮关闭DatePicker组件时，复原时间
                            this.dates = this.originalTime
                            // 上面时间复原后，数据虽然正确，但是子组件时间输入框和日历组件选中的日期都不对，所以需要用下面的代码手动设置一次
                            let beginTime = this.originalTime[0]
                            let endTime = this.originalTime[1]
                            if (beginTime && endTime) { // 没有数据时，不要进行下面的赋值操作
                                // 之所以填充时间是为了兼容浏览器，忘了是哪个浏览器了，没有填充数据就生成Date异常了
                                // 举个例子，当数据为‘2021-08-05 14’时，需要填充分钟，否则无法生成时间
                                beginTime = beginTime.length !== 13 ? beginTime : `${beginTime}:00`
                                endTime = endTime.length !== 13 ? endTime : `${endTime}:00`
                                this.$refs['datePicker'].internalValue =
                                    [new Date(beginTime),new Date(endTime)]
                                this.$refs['datePicker'].focusedDate = new Date(beginTime)
                            } else {
                                this.$refs['datePicker'].handleClear()
                            }
                        } else {
                            this.timeChange(this.dates)
                        }
                    }
                })
            },
            // 重新开始，起止时间修改，同下，需要手动绑定一次
            timeChange(timeArr){
                if(timeArr.length > 0){
                    this.$set(this.search, 'startTime', timeArr[0] ? (timeArr[0]+':00') : '')
                    this.$set(this.search, 'endTime', timeArr[1] ? (timeArr[1]+':00') : '')
                }
                if (new Date(timeArr[0]) >= new Date(timeArr[1])) {
                    this.$Message.warning('开始、结束时间不允许相同，无法查询')
                    this.total = 0
                    this.flowList = []
                    return
                }
                this.changePage(1)
            },
            // 查询源与目标列表
            queryflowfilter() {
                queryflowfilter({
                    projectId: this.$route.query.prjid
                }).then(({ code, message, data = {} }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                        return
                    }
                    this.dstDevices = data.dstDevices
                    this.srcDevices = data.srcDevices
                })
            },
            // 获取流量列表
            queryflowList() {
                queryflowList(this.search).then(({ code, data, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                    } else {
                        this.total = data.count || 0
                        // 结构返回数据的结构
                        this.flowList = (data || []).map(item => {
                            let result = item.result
                            Object.keys(result).forEach(key => {
                                item[key] = result[key]
                            })
                            return item
                        })
                    }
                }).catch(() => {
                    this.$Message.error('查询流量列表异常')
                })
            },
            changePage(page){
                this.pageIndex = page;
                this.queryflowList();
            },
        }
    }
</script>

<style scoped>
    .flow-list {
        height: calc(100% - 16px);
    }
    .flow-list .search-table {
        height: 100%;
    }
    .flow-list /deep/ #cardList {
        height: calc(100vh - 146px);
        max-height: unset;
    }
    .flow-list /deep/ #cardList .defGraphWrap {
        height: 100%;
    }
    .time /deep/ .ivu-date-picker-rel,
    .time /deep/ .ivu-date-picker-rel div {
        width: 100% !important;
    }
</style>